package authorization_code_postgres

import (
	"context"
	"fmt"
	"net/http"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/cloudwego/hertz/pkg/common/adaptor"
)

type userRoute struct {
}

func (r userRoute) Init(hertz *server.Hertz) {
	group := hertz.Group("/")
	group.POST("/login", r.Login())
	group.GET("/user", r.userinfo())
}

type LoginReq struct {
	Username string `json:"username"`
	Password string `json:"password"`
	Redirect string `json:"redirect"`
}

func (r userRoute) Login() app.HandlerFunc {
	return func(c context.Context, ctx *app.RequestContext) {

		//	---------------
		var loginReq LoginReq
		err := ctx.BindJSON(&loginReq)
		if err != nil {
			ctx.JSON(200, err)
			return
		}
		// 验证用户
		var user User
		if err := db.Where("username = ? AND password = ?", loginReq.Username, loginReq.Password).First(&user).Error; err != nil {
			ctx.JSON(http.StatusUnauthorized, "用户名或密码不正确")
			return
		}
		fmt.Println("user", user)

		//=============
		redirect := ctx.Query("redirect")
		fmt.Println("redirect", redirect)
		if redirect != "" {
			ctx.Redirect(http.StatusFound, []byte(redirect))
			return
		}
		ctx.JSON(200, "login success")
	}
}
func (r userRoute) userinfo() app.HandlerFunc {
	return func(c context.Context, ctx *app.RequestContext) {
		req, err := adaptor.GetCompatRequest(&ctx.Request)
		if err != nil {
			ctx.JSON(401, err.Error())
			return
		}
		/// 验证
		err = validateToken(req, Oauth2Server)
		if err != nil {
			ctx.JSON(401, err.Error())
			return
		}
		//	---------------
		// 获取令牌信息
		accessToken := ctx.Query("access_token") // 移除 "Bearer "
		var token Token
		if err := db.Where("access = ?", accessToken).First(&token).Error; err != nil {
			ctx.JSON(http.StatusUnauthorized, err)
			return
		}

		// 获取用户信息
		var user User
		if err := db.First(&user, token.UserID).Error; err != nil {
			ctx.JSON(http.StatusInternalServerError, err)
			return
		}

	}
}
